<template>
  <el-select v-model="zuzhi_value" @change="change">
    <el-option
      v-for="item in zuzhi"
      :key="item.org_id"
      :label="item.org_name"
      :value="item.org_id"
    />
  </el-select>
  &nbsp; &nbsp; &nbsp;
  <!-- <el-tree-select
    v-model="bumen_value"
    :data="bumen"
    check-strictly
    :render-after-expand="false"
    :props="{ value: 'dept_id', label: 'dept_name' }"
  /> -->
  <el-select v-model="bumen_value" @change="changed">
    <el-option
      v-for="item in bumen"
      :key="item.dept_id"
      :label="item.dept_name"
      :value="item.dept_id"
    />
  </el-select>
</template>

<script setup lang="ts">
import { onBeforeMount, ref } from 'vue'
import {
  ucMyDefaultOrgEditApi,
  ucMyDeptListApi,
  ucMyInfoApi,
  ucMyOrgListApi,
  ucMyDefaultDeptEditApi
} from './index'

import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()

const zuzhi_value: any = ref('') //选择的组织
let bumen_value: any = ref([]) // 选择的部门
let zuzhi: any = ref([]) //组织列表
const bumen: any = ref([]) // 部门列表

onBeforeMount(async () => {
  const res: any = await ucMyOrgListApi({ pageNo: 1, pageSize: 50, terminal_type: 3 })
    .catch(() => {})
    .finally(() => {})
  zuzhi.value = res.data
  zuzhi_value.value = wsCache.get('userInfo').default_org_id
  bumen_value.value = wsCache.get('userInfo').default_dept_name

  // 部门列表
  const red: any = await ucMyDeptListApi({
    my_org_id: Number(wsCache.get('userInfo').default_org_id)
  })
  bumen.value = red.data

  console.log(wsCache.get('userInfo'))
  // console.log(red.data, '部门')
})

// 修改组织
const change = async () => {
  // 修改默认组织
  await ucMyDefaultOrgEditApi({
    org_id: zuzhi_value.value
  })
  // 修改默认部门
  await ucMyDefaultDeptEditApi({ org_id: zuzhi_value.value, dept_id: '0' })

  // 用户信息
  const User = await ucMyInfoApi({})
  // 用户信息赋值本地
  wsCache.set('userInfo', User.data)
  wsCache.set('my_org_id', User.data.default_org_id)
  // console.log(User.data, '用户')
  bumen_value.value = []

  // 部门列表
  const red: any = await ucMyDeptListApi({
    my_org_id: zuzhi_value.value
  })
  bumen.value = red.data
}

// 修改默认部门
const changed = async () => {
  // 修改部门
  // wsCache.set('userInfo', JSON.parse(JSON.stringify(zuzhi_value.value)))
  await ucMyDefaultDeptEditApi({ org_id: zuzhi_value.value, dept_id: bumen_value.value })

  // 用户信息
  const User = await ucMyInfoApi({})
  // 用户信息赋值本地
  wsCache.set('userInfo', User.data)
  wsCache.set('my_org_id', User.data.default_org_id)
}
</script>

<style scoped></style>
